#include "Horde.h"
#include <algorithm>
#include <functional>

Horde::Horde()
{
    pr_Layer = NULL;
}

Horde::Horde(CLayer *pr_LayerPam)
{
    hordeMovementTimer.Init(1500);
    pr_Layer = pr_LayerPam;
    moveDirection = MOVE_RIGHT;
    alreadyMoved = false;
}

Horde::~Horde()
{
}

void Horde::Execute()
{
    HordeMovement();
    CheckLimit();
}

void Horde::HordeMovement()
{
    std::vector<Enemy*>::iterator itr;
    hordeMovementTimer.Update();
    if(hordeMovementTimer.Ended()){
        switch(moveDirection){
        case MOVE_RIGHT:
            for(itr=enemyList.begin();itr!=enemyList.end();itr++) (*itr)->Move(20,0);
            alreadyMoved=false;
            break;
        case MOVE_LEFT:
            for(itr=enemyList.begin();itr!=enemyList.end();itr++) (*itr)->Move(-20,0);
            alreadyMoved=false;
            break;
        }
        hordeMovementTimer.Restart();
    }
}

void Horde::CheckLimit()
{
    std::vector<Enemy*>::iterator itr;
    for(itr=enemyList.begin();itr!=enemyList.end();itr++){
        if((*itr)->Position.fx >= (640 - (*itr)->GetSize().fx)){
            if(!alreadyMoved)
                HordeMoveForward();
            moveDirection = MOVE_LEFT;
        }
        if((*itr)->Position.fx < 0){
            if(!alreadyMoved)
                HordeMoveForward();
            moveDirection = MOVE_RIGHT;
        }
    }
}

void Horde::HordeMoveForward()
{
    std::vector<Enemy*>::iterator itr;
    for(itr=enemyList.begin();itr!=enemyList.end();itr++){
        (*itr)->Move(0,50);
    }
    alreadyMoved=true;
}

void Horde::BringTheHorde()
{
    for(int i=0;i<HORDE_SIZE;i++){
        EnemyCreate(CVector(i*60,0));
    }
}

void Horde::EnemyCreate(const CVector& cv)
{
    Enemy* enemy = new Enemy();
    enemy->lifePoints = 1;
    enemy->name = "intruder";
    enemy->Position = cv;
    enemy->bCanShot = true;
    enemyList.push_back(dynamic_cast<Enemy*>(pr_Layer->AddSprite(enemy)));
}
